<template>
  <div class="box">
    <div class="card-container">
      <el-row :gutter="10">
      <el-form :model="queryParams" ref="queryForm" label-width="100px" :inline="true" v-show="showSearch">
        <el-col :span="19" :offset="0">
          <el-form-item label="设备序列号" prop="code">
            <el-input v-model="queryParams.code" :style="'width:215px'" placeholder="请输入设备序列号" clearable size="small"
              @keyup.enter.native="handleQuery" />
          </el-form-item>

          <el-form-item label="设备类型" prop="deviceType">
            <el-select v-model="queryParams.deviceType" clearable :style="'width:215px'" placeholder="请选择设备类型">
              <el-option v-for="item in this.dict.type.sys_device_mode" :key="item.value" :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="软件版本" prop="version">
            <el-input v-model="queryParams.version" :style="'width:215px'" placeholder="请输入软件版本" clearable size="small"
              @keyup.enter.native="handleQuery" />
          </el-form-item>

          <el-form-item label="接入时间" prop="accessTime">
            <el-date-picker clearable size="small" style="width: 215px" v-model="queryParams.accessTime" type="date"
              value-format="yyyy-MM-dd" placeholder="选择接入时间">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="校验状态" prop="checkStatus">
            <el-select v-model="queryParams.checkStatus" clearable :style="'width:215px'" placeholder="请选择效验状态">
              <el-option :label="'全部'" :value="null"></el-option>
              <el-option v-for="item in this.dict.type.sys_check_state" :key="item.value" :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5" :offset="0">
          <el-form-item>
            <el-button  icon="el-icon-search" size="mini" @click="handleQuery">搜索
            </el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    </div>
   
    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button   icon="el-icon-delete" size="mini" @click="handleDeleteAll">全部清除</el-button>
      </el-col>
    </el-row> -->
    <div class="card-container">
      <div class="body-title">
        <div class="body-title-left">接入设备</div>
        <div class="body-title-right">
          <el-button icon="el-icon-delete" size="mini" @click="handleDeleteAll">全部清除</el-button>
          <!-- <el-button  size="mini" :disabled="single" v-show="!multiple" @click="handleUpdate">
            修改</el-button> -->
          <!-- <el-button  size="mini" :disabled="multiple" v-hasPermi="['device:remove']" v-show="!multiple"
            @click="handleDelete">删除</el-button> -->
          <!-- <el-button  size="mini" v-show="!multiple" @click="handleExport">导出</el-button> -->
          <!-- <el-button   icon="el-icon-plus" size="mini" @click="handleAdd">新增
          </el-button> -->
          <!-- <el-button  size="mini" @click="handleDeleteAll">全部清除
          </el-button> -->
        </div>
      </div>
      <!-- @selection-change="handleSelectionChange" -->
      <el-table v-loading="loading" height="450" :data="deviceList">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="接入时间" show-overflow-tooltip align="center" prop="accessTime" width="180">
          <template slot-scope="scope">
            <!-- <span>{{ parseTime(scope.row.accessTime, '{y}-{m}-{d}') }}</span> -->
            <span>{{ scope.row.accessTime }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="设备管理" align="center" prop="deviceId" /> -->
        <el-table-column label="设备序列号" align="center" prop="code" />
        <el-table-column label="站点名称" align="center" prop="siteName" />
        <el-table-column label="软件版本" align="center" prop="softwareVersion" />
        <el-table-column label="设备类型" align="center" prop="deviceTypeLabel" />
        <!-- <el-table-column label="用户名" align="center" prop="userName" />
        <el-table-column label="密码" align="center" prop="password" /> -->
        <el-table-column label="校验状态" align="center" prop="checkStatus">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_check_state" :value="scope.row.checkStatus" />
          </template>
        </el-table-column>
        <el-table-column label="在线状态"  min-width="80" align="center" prop="onlineStatus">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_on_line_status" :value="scope.row.onlineStatus" />
          </template>
        </el-table-column>
        <el-table-column label="备注" show-overflow-tooltip align="center" prop="remark" />
        <el-table-column label="校验时间" show-overflow-tooltip align="center" prop="checkTime" width="180">
          <template slot-scope="scope">
            <!-- <span>{{ parseTime(scope.row.checkTime, '{y}-{m}-{d}') }}</span> -->
            <span>{{ scope.row.checkTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" :disabled="scope.row.checkStatus == '1'" v-hasPermi="['device:edit']"
              @click="handleUpdate(scope.row)">
              校验</el-button>
            <el-button size="mini" type="text" v-hasPermi="['deviceParam:query']"
              @click="handleParam(scope.row)">参数</el-button>
            <el-button size="mini" type="text" v-hasPermi="['deviceParam:query']"
              @click="handleDelete(scope.row)">清除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <!-- 效验 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-row :gutter="10">
        <el-form ref="form" :label-position="'top'" :model="form" :rules="rules" label-width="80px">
          <el-col :span="8" :offset="0">
            <el-form-item label="设备序列号" prop="code">
              <el-input v-model="form.code" disabled placeholder="请输入设备序列号" />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="站点名称" prop="siteName">
              <el-input v-model="form.siteName" disabled placeholder="请输入站点名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="软件版本" prop="version">
              <el-input v-model="form.version" disabled placeholder="请输入软件版本" />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="设备类型" prop="deviceType">
              <el-select v-model="form.deviceType" @change="handleModeType" disabled :style="'width:280px'"
                placeholder="请选择设备类型">
                <el-option v-for="item in dict.type.sys_device_mode" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="设备型号" prop="modelId">
              <el-select v-model="form.modelId" @change="handleMode" :disabled="form.type == null" :style="'width:280px'"
                placeholder="请选择设备型号">
                <el-option v-for="item in modList" :key="item.modelId" :label="item.model" :value="item.modelId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8" :offset="0">
            <el-form-item label="设备厂商" prop="facId">
              <el-select v-model="form.facId" disabled :style="'width:280px'" placeholder="请选择设备厂商">
                <el-option v-for="item in factList" :key="item.facId" :label="item.facturer" :value="item.facId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="8" :offset="0">
            <el-form-item label="所属项目" prop="projectId">
              <!-- <el-input v-model="form.version" placeholder="请输入软件版本" /> -->
              <el-select v-model="form.projectId" :style="'width:100%'" placeholder="请选择所属项目">
                <el-option v-for="item in projectList" :key="item.projectId" :label="item.shortName"
                  :value="item.projectId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8" :offset="0">
            <el-form-item label="地址" prop="deviceAddress">
              <el-cascader :style="'width: 279px'" :props="{ children: 'child', value: 'code', label: 'name' }"
                :clearable="true" :options="chinaArea" v-model="form.deviceAddress">
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="详情地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入详情地址" />
            </el-form-item>
          </el-col>

          <el-col :span="8" :offset="0">
            <el-form-item label="经度" prop="pLongitude">
              <el-input v-model.number="form.pLongitude" disabled type="number" placeholder="请输入经度">
                <template slot="append">度</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="纬度" prop="pLatitude">
              <el-input v-model.number="form.pLatitude" disabled type="number" placeholder="请输入纬度">
                <template slot="append">度</template>
              </el-input>
            </el-form-item>
          </el-col> -->

          <!-- <el-col :span="24" :offset="0">
            <el-form-item label="地图" prop="">
              <new-map ref="map" @updateLocation="updateLocation"></new-map>
            </el-form-item>
          </el-col> -->
          <el-col :span="24" :offset="0">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button  @click="submitForm('1')">通 过</el-button>
        <el-button v-if="form.checkStatus !== '2'" @click="submitForm('2')">拒 绝</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 参数详情 -->
    <el-dialog title="参数详情" v-if="paramOpen" :visible.sync="paramOpen" width="750px" append-to-body
      :close-on-click-modal="false">
      <!-- @out="cancelParam" -->
      <param-list ref="paramList" :register="false" :search-data="paramList" />
    </el-dialog>
  </div>
</template>

<script>
import { getProject } from "@/api/runningLog/runningLog.js";
import {
  listDevice,
  getDevice,
  delDevice,
  addDevice,
  updateDevice,
} from "@/api/device/device";
// import paramList from './parameters.vue';
import paramList from "@/views/components/parameters";
import newMap from "@/components/aliMap/index.vue";

export default {
  name: "Device",
  dicts: ["sys_device_mode", "sys_check_state",'sys_on_line_status'],
  data() {
    return {
      modList: [],
      factList: [],
      paramList: {},
      paramOpen: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 接入设备表格数据
      deviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        accessTime: null,
        code: null,
        version: null,
        type: null,
        checkStatus: null,
        deviceType: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
        modelId: [
          { required: true, message: "设备型号不能为空", trigger: "change" },
        ],
        // deviceAddress: [
        //   { required: true, message: '地址不能为空', trigger: 'change' },
        // ],
        deviceType: [
          { required: true, message: "设备类型不能为空", trigger: "change" },
        ],
        facId: [
          { required: true, message: "设备厂商不能为空", trigger: "change" },
        ],
        projectId: [
          { required: true, message: "所属项目不能为空", trigger: "change" },
        ],
      },
      chinaArea: [],
      projectList: [],
    };
  },
  created() {
    this.getList();
  },
  activated() {
    this.getList();
  },
  components: {
    paramList,
    newMap,
  },
  methods: {
    // updateLocation(Addr) {
    //   console.log("位置信息：", Addr);
    //   this.form.pLongitude = Addr.lon;
    //   this.form.pLatitude = Addr.lat;
    //   this.form.address = Addr.orgAddr;
    //   let addressCode = [];
    //   this.chinaArea.forEach((item1) => {
    //     if (item1.code.slice(0, 2) == Addr.adcode.slice(0, 2)) {
    //       addressCode.push(item1.code);
    //       item1.child.forEach((item2) => {
    //         if (item2.code.slice(2, 4) == Addr.adcode.slice(2, 4)) {
    //           addressCode.push(item2.code);
    //           item2.child.forEach((item3) => {
    //             if (item3.code.slice(4, 6) == Addr.adcode.slice(4, 6)) {
    //               addressCode.push(item3.code);
    //             }
    //           });
    //         }
    //       });
    //     }
    //   });
    //   this.form.deviceAddress = addressCode;
    // },
    // 省市区联动变化后
    // handleAddress(val) {
    //   console.log(val);
    //   if (val?.length > 0) {
    //     this.form.address = "";
    //     let addressName = [];
    //     this.chinaArea.forEach((item1) => {
    //       if (item1.code == val[0]) {
    //         addressName.push(item1.name);
    //         item1.child.forEach((item2) => {
    //           if (item2.code == val[1]) {
    //             addressName.push(item2.name);
    //             item2.child.forEach((item3) => {
    //               if (item3.code == val[2]) {
    //                 addressName.push(item3.name);
    //               }
    //             });
    //           }
    //         });
    //       }
    //     });
    //     console.log(addressName);
    //     getLnglat({
    //       adCode: val[2],
    //       city: addressName[1],
    //       area: addressName[2],
    //     }).then((response) => {
    //       console.log("response.data", response.data);
    //       if (Object.keys(response.data).length > 0) {
    //         this.form.pLongitude = response.data.longitude;
    //         this.form.pLatitude = response.data.latitude;
    //         this.$refs.map.mapDraw(
    //           [this.form.pLongitude, this.form.pLatitude],
    //           this.form.address || ""
    //         );
    //       }
    //     });
    //   }
    // },
    // async getArea() {
    //   let res = await getChinaArea();
    //   if (res.code == 200) {
    //     this.chinaArea = res.data;
    //   }
    // },
    // async getFact() {
    //   let res = await getFacturerInfo();
    //   if (res.code == 200) {
    //     this.factList = res.data;
    //   }
    // },
    handleMode(type) {
      const facId = this.modList.filter((item) => {
        return item.modelId == type;
      })[0].facId;
      this.form.facId = facId;
    },
    // 全部清除
    handleDeleteAll() {
      const deviceIds = [];
      this.deviceList.forEach((item) => {
        deviceIds.push(item.deviceId)
      })
      console.log(deviceIds, "deviceIds")
      this.$modal
        .confirm("是否确认全部删除设备？")
        .then(function () {
          return delDevice(deviceIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("全部删除成功");
        })
        .catch(() => { });
      // this.deviceList = []
    },
    async handleModeType(type) {
      let data = await this.$api.getMod({ type: this.form.deviceType });
      this.modList = data;
      this.form.facId = null;
      this.form.modelId = null;
    },
    handleParam(row) {
      this.paramOpen = true;
      this.paramList = row;
    },
    cancelParam() {
      this.paramOpen = false;
      // this.reset();
      this.$refs["paramList"].reset();
    },
    /** 查询设备管理列表 */
    getList() {
      this.loading = true;
      listDevice(this.queryParams).then((response) => {
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deviceId: null,
        accessTime: null,
        code: null,
        siteName: null,
        version: null,
        type: null,
        userName: null,
        password: null,
        checkStatus: null,
        remark: null,
        checkTime: null,
        modelId: null,
        facId: null,
        projectId: null,
        // pLongitude: null,
        // pLatitude: null,
        // province: null,
        // city: null,
        // area: null,
        // address: null,
        status: "0",
        delFlag: null,
        delTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        // deviceAddress: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.deviceId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.title = "校验";
      this.open = true;
      const deviceId = row.deviceId || this.ids;
      getDevice(deviceId).then(async (response) => {
        this.form = response.data;
        // this.chinaArea = await this.$api.getArea();
        this.factList = await this.$api.getFactAll();
        this.modList = await this.$api.getMod({ type: this.form.deviceType });
        // this.handleModeType();
        const res = await getProject();
        if (res.code == 200) {
          this.projectList = res.data;
        }
        // this.$nextTick(() => {
        //   this.$refs.map.mapDraw(
        //     [this.form.pLongitude, this.form.pLatitude],
        //     this.form.address
        //   );
        // });
      });
    },
    /** 提交按钮 */
    submitForm(type) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.deviceId != null) {
            this.form.checkStatus = type;
            updateDevice(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDevice(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceIds = row.deviceId || this.ids;
      this.$modal
        .confirm("是否确认删除设备？")
        .then(function () {
          return delDevice(deviceIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "device/device/export",
        {
          ...this.queryParams,
        },
        `device_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.box {
  width: 100%;
  height: 100%;
  padding: 20px;
}



.body-title {
  display: flex;
  position: relative;
  // justify-content: space-between;
  align-items: center;
}

.body-title-left {
  height: 100%;
  font-size: 16px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 600;
  color: #fff;
  line-height: 64px;
}

.body-title-right {
  position: absolute;
  right: 0;
}

::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}

::v-deep input[type="number"] {
  -moz-appearance: textfield !important;
  // appearance: textfield !important;
}
</style>
